package com.ailanyin.security.service;

import cn.hutool.core.util.StrUtil;
import com.ailanyin.common.service.RedisService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Service;

/**
 * @author ailanyin
 * @version 1.0
 * @since 2021/10/26 0026 下午 17:32
 */
@Service
public class SecurityUserService {

    @Autowired
    private RedisService redisService;

    private static String userDetails_redis_key = ":login:loginUsers:";

    /**
     * 添加登录用户的 UserDetails
     *
     * @param username    key
     * @param userDetails value
     */
    public void addUserDetailsToCache(String username, UserDetails userDetails) {
        // 86400 = one day
        redisService.set(userDetails_redis_key + username, userDetails, 86400);
    }

    /**
     * 删除登录用户的 UserDetails
     *
     * @param username key
     */
    public void delUserDetailsFromCache(String username) {
        if (StrUtil.isNotEmpty(username)) {
            redisService.del(userDetails_redis_key + username);
        }
        //删除SecurityContext上下文中的信息
        SecurityContextHolder.clearContext();
    }

    /**
     * 获取登录用户的 UserDetails
     *
     * @param username key
     * @return UserDetails
     */
    public UserDetails getUserDetailsFromCache(String username) {
        return (UserDetails) redisService.get(userDetails_redis_key + username);
    }
}
